package com.dangdi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.nio.CharBuffer;

public class SocketClient {
    private String host = "127.0.0.1";
    private int port = 5555;
    Logger logger = LoggerFactory.getLogger(this.getClass());
    InputStream inputStream = null;
    OutputStream outputStream = null;
    Socket socket = null;

    public SocketClient() {
    }

    /**
     * 数据发送线程
     */
    class SendThread implements Runnable {
        private Socket socket;

        public SendThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            int c = 5;
            while (true) {
                c--;
                if (c == 0) {
                    break;
                }
                try {
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(
                            socket.getOutputStream()));
                    pw.write("我是客户端张群");
                    pw.flush();
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 数据接收线程
     */
    class ReceiveThread implements Runnable {
        private Socket socket;

        public ReceiveThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            while (true) {
                try {
                    Reader reader = new InputStreamReader(
                            socket.getInputStream());
                    CharBuffer charBuffer = CharBuffer.allocate(8192);
                    int charIndex = -1;
                    while ((charIndex = reader.read(charBuffer)) != -1) {
                        charBuffer.flip();
                        System.out.println("client--> " + charBuffer.toString());
                    }
                } catch (IOException e) {
                    System.out.println("client-->服务器不可用");
                    break;
                }
            }
        }
    }

    private void start() {
        try {
            Socket socket = new Socket(host, port);// 创建Socket
            new Thread(new SendThread(socket)).start();//
            new Thread(new ReceiveThread(socket)).start();// 启动收线程
        } catch (Exception e) {
            logger.info("启动线程发生错误:" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        new SocketClient().start();
    }

}